import { latitude, longitude } from '@/business/carMarker'
import { Map, Marker, TileLayer } from 'maptalks'
import { map } from './base'

/**
 * 底图图层
 */
export let baseLayer1: TileLayer

/**
 * 地图实例
 */
export let map1: Map

/**
 * 设置各缩放等级分辨率
 * @returns 各缩放等级分辨率
 */
const initResolutions = () => {
  const result = []
  const d = 2 * 6378137 * Math.PI
  for (let i = 0; i < 25; i++) {
    result[i] = d / (256 * Math.pow(2, i))
  }
  return result
}

/**
 * 初始化地图
 */
export const initMapShow = (mapRef: HTMLDivElement) => {
  map1 = new Map(mapRef, {
    spatialReference: {
      resolutions: initResolutions()
    },
    center: map.getCenter(),
    zoom: map.getZoom() - 1,
    draggable: false,
    scrollWheelZoom: false,
    dblClickZoom: false,
    // minZoom: 11,
    baseLayer: initBaseLayer()
  })
  map.on('moving moveend', function () {
    const point = new Marker([longitude.value, latitude.value], {})
    map1.setCenter(point.getCenter())
  })

  map.on('zooming zoomend', function () {
    const point = new Marker([longitude.value, latitude.value], {})
    map1.setCenterAndZoom(point.getCenter(), map.getZoom() - 1)
  })
}

/**
 * 初始化底图图层
 * @returns 地图图层实例
 */
const initBaseLayer = () => {
  baseLayer1 = new TileLayer('base', {
    maxAvailableZoom: 19,
    urlTemplate: '/tiles/{z}/{x}/{y}.jpg',
    tileSystem: [1, 1, -20037508.34, -20037508.34]
  })
  return baseLayer1
}
